import React,{useState,useEffect} from 'react'
import { Space, Table, Tag , Button} from 'antd';
import axios from '../../utils/axios';
import Mymodal from "../../components/Mymodal"
import AddModal from '../../components/addModal';
function List() {
  let [delmodalopen,setDelmodalopen] = useState(false)
  let [delIndex,setDelIndex] = useState(0)
  let [addmodalopen,setAddmodalopen] = useState(false)
  let [editIndex,setEidtINDX] = useState(0)
  let [eitItem,setEditItem] = useState({})
  let [isadd,setIsadd]= useState("新增")
  let [columns,setColums] = useState([
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <a>{text}</a>,
    },
    {
      title: 'date',
      dataIndex: 'date',
      key: 'age',
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: 'Action',
      key: 'action',
      render: (_, record,index) => (
        <Space size="middle">
          <a onClick={()=>editfn(record,index)}>编辑</a>
          <a onClick={()=>delfn(index)}>Delete</a>
        </Space>
      ),
    },
  ])
  let [arr,setArr] = useState([])
  useEffect(()=>{
    axios.get("/api/list").then(res=>{
      setArr(res.data)
    })
  },[])
  let editfn = (record,index)=>{
      console.log(record,index);
      setIsadd("编辑")
      setEidtINDX(index)
      setEditItem(record)
      setAddmodalopen(true)
  }
  let delfn = (index)=>{
    console.log(index);
    setDelmodalopen(true)
    setDelIndex(index)
  }
  let closedelmodal = (data)=>{ // 该方法用于接受子组件参数
      setDelmodalopen(data.close)
      if (data.isclose === "确定") {
        let newarr = [...arr]
        newarr.splice(delIndex,1)
        setArr(newarr)
      }
  }
  let addfn = ()=>{ // 新增的点击事件
      setAddmodalopen(true)
      setIsadd("新增")
  }
  let closeaddmodalfn = (data)=>{
     setAddmodalopen(data.close)
     if (data.isadd === "新增" && data.values) {
       data.values.key = Math.random()
       let newarr = [...arr]
        newarr.unshift(data.values)
        setArr(newarr)
     } else if (data.isadd === "编辑" && data.values ) {
         data.values.key = Math.random()
         let newarr = [...arr]
         newarr.splice(editIndex,1,data.values)
         setArr(newarr)
     }
  }
  return (
    <div>
       <Button onClick={addfn}>新增</Button>
      <Table columns={columns} dataSource={arr} />
      <Mymodal delmodalopen={delmodalopen} delIndex={delIndex} closedelmodal={closedelmodal}></Mymodal>
      <AddModal addmodalopen={addmodalopen} closeaddmodalfn={closeaddmodalfn} isadd={isadd} editIndex={editfn} eitItem={eitItem}></AddModal>
    </div>
  )
}

export default List